package practise.案例九_文件下载;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Service {
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket = new ServerSocket(55555);
        while (true) {
            Socket socket = serverSocket.accept();
            new Thread(new MyRunnable(socket)).start();
        }
    }
}

class MyRunnable implements Runnable {
    private Socket socket ;

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    public MyRunnable(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            BufferedInputStream bufferedInputStream = new BufferedInputStream(
                    new FileInputStream("day11/src/practise/案例九_文件下载/file/img-00.jpg"));
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(socket.getOutputStream());
            byte[] bytes = new byte[1024*64];
            int len ;
            while ((len = bufferedInputStream.read(bytes)) != -1) {
                bufferedOutputStream.write(bytes,0,len);
            }
//            bufferedOutputStream.flush();
//            socket.shutdownOutput();

            bufferedOutputStream.write("文件下载完成".getBytes());
            bufferedOutputStream.flush();

            bufferedOutputStream.close();
            bufferedInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}